#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <pthread.h>
#include <string.h>
#include <functional>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <memory>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "Socket.hpp"
using namespace std;
using namespace socket_ns;

class TcpServer;

using io_service_t = function<void(socket_sptr sockfd, InetAddr client)>;

class ThreadData
{
public:
    ThreadData(socket_sptr fd, InetAddr addr, TcpServer *s) : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, io_service_t service)
        : _localaddr("0", port), _listensock(make_unique<TcpSocket>()), _isrunning(false), _service(service)
    {
        _listensock->BuildListenSocket(_localaddr);
    }

    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }
    void Loop() // 循环
    {
        _isrunning = true;
        // 不能直接接受数据，要先获取连接
        // 连接用 accept
        while (_isrunning)
        {
            InetAddr peeraddr;
            socket_sptr normalsock = _listensock->Accepter(&peeraddr);
            // Version 2:多线程
            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&t, nullptr, HandlerSock, td); // 将线程分离
        }
    }
    ~TcpServer()
    {
    }

private:
    InetAddr _localaddr;
    unique_ptr<Socket> _listensock;
    bool _isrunning;
    io_service_t _service;
};

// void Service(socket_sptr sockfd, InetAddr client)
// {
//     LOG(DEBUG, "get a new link,info %s:%d\n", client.Ip().c_str(), client.Port());
//     std::string clientaddr = "[" + client.Ip() + ":" + std::to_string(client.Port()) + "]# ";
//     while (true)
//     {
//         char inbuffer[1024];
//         ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
//         if (n > 0)
//         {
//             inbuffer[0];
//             cout << clientaddr << inbuffer << endl;
//             std::string echo_string = "[server echo]# ";
//             echo_string += inbuffer;

//             write(sockfd, echo_string.c_str(), echo_string.size());
//         }
//         else if (n == 0)
//         {
//             // client 关闭了
//             LOG(INFO, "%s quit\n", clientaddr.c_str());
//             break;
//         }
//         else
//         {
//             LOG(ERROR, "read error\n", clientaddr.c_str());
//             break;
//         }
//     }
//     close(sockfd);
// }